package com.problem.queue;

/**
 * https://leetcode-cn.com/explore/learn/card/queue-stack/216/queue-first-in-first-out-data-structure/866/
 */
public class MyCircularQueue {
    private int start=-1;
    private int end=-1;
    private int size;
    private int[] l;
    /** Initialize your data structure here. Set the size of the queue to be k. */
    public MyCircularQueue(int k) {
        l = new int[k];
        this.size = k;
    }

    /** Insert an element into the circular queue. Return true if the operation is successful. */
    public boolean enQueue(int value) {
        if (isFull()) {
            //满了返回false
            return false;
        }
        if (isEmpty()) {
            end=0;
            start=0;
        }else if (end == size - 1) {
            end = 0;
        } else {
            end++;
        }
        l[end] = value;
        return true;
    }

    /** Delete an element from the circular queue. Return true if the operation is successful. */
    public boolean deQueue() {
        if (isEmpty()) {
            return false;
        }
        if (start == end) {
            start = -1;
            end = -1;
            l = new int[size];
        } else {
            int[] newArr = new int[size];
            for (int i=0;i<l.length;i++) {
                if (i == start) {
                    continue;
                }
                newArr[i] = l[i];
            }
            l = newArr;
            if (start == size - 1) {
                start = 0;
            } else {
                start ++;
            }
        }
        return true;
    }

    /** Get the front item from the queue. */
    public int Front() {
        if (isEmpty()) {
            return -1;
        }
        return l[start];
    }

    /** Get the last item from the queue. */
    public int Rear() {
        if (isEmpty()) {
            return -1;
        }
        return l[end];
    }

    /** Checks whether the circular queue is empty or not. */
    public boolean isEmpty() {
        return start==-1&& end==-1;
    }

    /** Checks whether the circular queue is full or not. */
    public boolean isFull() {
        return (end-start== -1 || start==0&& end==size-1)?true:false;
    }

    public static void main(String[] args) {
        MyCircularQueue queue = new MyCircularQueue(4);
        System.out.println(queue.enQueue(3));
        System.out.println(queue.Front());
        System.out.println(queue.isFull());
        System.out.println(queue.enQueue(7));
        System.out.println(queue.enQueue(2));
        System.out.println(queue.enQueue(5));
        System.out.println(queue.deQueue());
        System.out.println(queue.enQueue(4));
        System.out.println(queue.enQueue(2));
        System.out.println(queue.isEmpty());
        System.out.println(queue.Rear());
    }
}
